<template>
  <div class="simple-form-preview">
    <div class="preview-header">
      <h3>表单预览</h3>
      <div class="preview-actions">
        <Button type="primary" @click="submitForm" :loading="submitting">
          <IconifyIcon icon="ant-design:check-outlined" />
          提交表单
        </Button>
        <Button @click="resetForm">
          <IconifyIcon icon="ant-design:reload-outlined" />
          重置表单
        </Button>
      </div>
    </div>

    <div class="preview-content">
      <div v-if="fields.length === 0" class="empty-state">
        <IconifyIcon icon="ant-design:form-outlined" class="empty-icon" />
        <p>暂无字段配置，请先在"属性结构"中添加字段</p>
      </div>

      <Form
        v-else
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        layout="horizontal"
      >
        <FormItem
          v-for="field in fields"
          :key="field.id"
          :label="field.label"
          :name="field.name"
          :rules="getFieldRules(field)"
        >
          <!-- 文本输入 -->
          <Input
            v-if="field.type === 'STRING'"
            v-model:value="formData[field.name]"
            :placeholder="field.uiConfig?.placeholder || `请输入${field.label}`"
          />

          <!-- 数字输入 -->
          <InputNumber
            v-else-if="field.type === 'NUMBER'"
            v-model:value="formData[field.name]"
            :placeholder="field.uiConfig?.placeholder || `请输入${field.label}`"
            style="width: 100%"
          />

          <!-- 布尔开关 -->
          <Switch
            v-else-if="field.type === 'BOOLEAN'"
            v-model:checked="formData[field.name]"
          />

          <!-- 日期选择 -->
          <DatePicker
            v-else-if="field.type === 'DATE'"
            v-model:value="formData[field.name]"
            :placeholder="field.uiConfig?.placeholder || `请选择${field.label}`"
            style="width: 100%"
          />

          <!-- 下拉选择 -->
          <Select
            v-else-if="field.type === 'SELECT'"
            v-model:value="formData[field.name]"
            :placeholder="field.uiConfig?.placeholder || `请选择${field.label}`"
            :options="getSelectOptions(field)"
          />

          <!-- 多行文本 -->
          <Textarea
            v-else-if="field.type === 'TEXTAREA'"
            v-model:value="formData[field.name]"
            :placeholder="field.uiConfig?.placeholder || `请输入${field.label}`"
            :rows="4"
          />

          <!-- 文件上传 -->
          <Upload
            v-else-if="field.type === 'UPLOAD'"
            v-model:file-list="formData[field.name]"
            :placeholder="field.uiConfig?.placeholder || `请上传${field.label}`"
          >
            <Button>
              <IconifyIcon icon="ant-design:upload-outlined" />
              点击上传
            </Button>
          </Upload>

          <!-- 默认文本输入 -->
          <Input
            v-else
            v-model:value="formData[field.name]"
            :placeholder="field.uiConfig?.placeholder || `请输入${field.label}`"
          />
        </FormItem>
      </Form>
    </div>

    <div v-if="Object.keys(formData).length > 0" class="preview-data">
      <h4>表单数据</h4>
      <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue';
import {
  Button,
  Form,
  FormItem,
  Input,
  InputNumber,
  Switch,
  DatePicker,
  Select,
  Textarea,
  Upload,
  message,
} from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// Props
const props = defineProps<{
  fields: any[];
}>();

// 响应式数据
const submitting = ref(false);
const formData = reactive({});

// 获取字段验证规则
const getFieldRules = (field: any) => {
  const rules: any[] = [];
  rulesrules;

  // 必填验证
  if (field.required) {
    rules.push({
      required: true,
      message: `请${field.type === 'SELECT' ? '选择' : '输入'}${field.label}`,
    });
  }

  // 添加其他验证规则
  if (field.validation) {
    if (field.validation.min !== undefined) {
      rules.push({
        min: field.validation.min,
        message: `${field.label}不能少于${field.validation.min}`,
      });
    }
    if (field.validation.max !== undefined) {
      rules.push({
        max: field.validation.max,
        message: `${field.label}不能超过${field.validation.max}`,
      });
    }
    if (field.validation.pattern) {
      rules.push({
        pattern: new RegExp(field.validation.pattern),
        message: `${field.label}格式不正确`,
      });
    }
  }

  return rules;
};

// 获取选择框选项
const getSelectOptions = (field: any) => {
  if (field.options && field.options.length > 0) {
    return field.options;
  }

  // 默认选项
  return [
    { label: '选项1', value: 'option1' },
    { label: '选项2', value: 'option2' },
    { label: '选项3', value: 'option3' },
  ];
};

// 提交表单
const submitForm = async () => {
  submitting.value = true;
  try {
    // 简单的表单验证
    const hasErrors = props.fields.some((field) => {
      if (field.required && !formData[field.name]) {
        message.error(
          `请${field.type === 'SELECT' ? '选择' : '输入'}${field.label}`,
        );
        return true;
      }
      return false;
    });

    if (hasErrors) {
      return;
    }

    message.success('表单提交成功！');
    console.log('表单数据:', formData);
  } catch (error) {
    message.error('表单提交失败: ' + (error as Error).message);
  } finally {
    submitting.value = false;
  }
};

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach((key) => {
    delete formData[key];
  });
  message.success('表单已重置');
};

// 监听字段变化，初始化表单数据
watch(
  () => props.fields,
  (newFields) => {
    // 清除旧数据
    Object.keys(formData).forEach((key) => {
      delete formData[key];
    });

    // 初始化新字段的默认值
    newFields.forEach((field) => {
      if (field.defaultValue !== undefined) {
        formData[field.name] = field.defaultValue;
      } else {
        // 根据字段类型设置默认值
        switch (field.type) {
          case 'BOOLEAN':
            formData[field.name] = false;
            break;
          case 'NUMBER':
            formData[field.name] = undefined;
            break;
          case 'UPLOAD':
            formData[field.name] = [];
            break;
          default:
            formData[field.name] = '';
        }
      }
    });
  },
  { immediate: true, deep: true },
);
</script>

<style lang="less" scoped>
.simple-form-preview {
  .preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h3 {
      margin: 0;
      color: #262626;
    }

    .preview-actions {
      display: flex;
      gap: 8px;
    }
  }

  .preview-content {
    margin-bottom: 20px;
  }

  .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #8c8c8c;

    .empty-icon {
      font-size: 48px;
      margin-bottom: 16px;
      color: #d9d9d9;
    }

    p {
      margin: 0;
      font-size: 14px;
    }
  }

  .preview-data {
    border-top: 1px solid #f0f0f0;
    padding-top: 20px;

    h4 {
      margin: 0 0 12px 0;
      color: #262626;
      font-size: 14px;
    }

    pre {
      background-color: #f5f5f5;
      padding: 12px;
      border-radius: 4px;
      font-size: 12px;
      color: #595959;
      margin: 0;
      overflow-x: auto;
      max-height: 200px;
      overflow-y: auto;
    }
  }
}
</style>
